package helpers

import (
	"LearnProject/conf"
	"encoding/json"
	"fmt"
	"net/http"
)

//输出格式内容
type OutFormat struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Data interface{} `json:"data"`
}


//格式化输出到
func JsonOut(w http.ResponseWriter, data interface{}) {

	//输出格式规整
	outFormat := &OutFormat{
		Code: 0,
		Msg: "ok",
	}

	//参数赋值
	outFormat.Data = data
	outPrint(w, outFormat)
}

//格式化输出到
func JsonErrorOut(w http.ResponseWriter, data interface{}, errCode int) {

	//输出格式规整
	outFormat := &OutFormat{
		Code: errCode,
		Msg: conf.GetEerorCode(errCode),
	}

	//参数赋值
	outFormat.Data = data
	outPrint(w, outFormat)
}


//格式化输出部分
func outPrint(w http.ResponseWriter, data *OutFormat) {
	//转为json格式
	outdata, err := json.Marshal(&data)
	if err != nil {
		fmt.Fprintf(w, "{}")
	}

	//设置输出头
	w.Header().Set("content-type", "application/json")
	fmt.Fprint(w, string(outdata))
}